package com.wxg.json;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.junit.Ignore;
import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.wxg.json.bean.CommandBean;

public class CommandBeanJsonDB {

	/**
	 * java.io.tmpdir
	 * user.home
	 */
	private static final String JSON_FILE_NAME = System.getProperty("user.home") + "\\wxg-toolkit\\commandbean.json";
	
	private List<CommandBean> cblist;
	
	private static final int SHOW_COLUMN_SIZE = 4;
	
	private List<String> headlist;
	
	private Object[][] cachedatas;
	
	private String[] cacheheads;
	
	public CommandBeanJsonDB(){
		//cblist = new ArrayList<CommandBean>();
		try {
			loadDataFromJsonFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		headlist = new ArrayList<String>();
		head("Name", "Command", "Directory", "Port");
	}
	
	public void head(String ...args){
		if(null != args){
			for(String arg : args){
				headlist.add(arg);
			}
		}
	}
	
	public String[] head(){
		if(null == cacheheads || cacheheads.length != headlist.size()){
			cacheheads = headlist.toArray(new String[]{});
		}
		return cacheheads;
	}
	
	public void data(String name, String command){
		CommandBean cb = new CommandBean(name, command);
		cblist.add(cb);
	}
	
	public void data(String name, String command, String dir){
		CommandBean cb = new CommandBean(name, command, dir);
		cblist.add(cb);
	}
	
	public void data(String name, String command, String dir, String port){
		CommandBean cb = new CommandBean(name, command, dir, port);
		cblist.add(cb);
	}
	
	public Object[][] data(){
		int size = cblist.size();
		if(null == cachedatas || cachedatas.length != size){
			cachedatas = new Object[size][SHOW_COLUMN_SIZE];
			for(int i=0; i<size; i++){
				CommandBean bean = cblist.get(i);
				cachedatas[i][0] = bean.getName();
				cachedatas[i][1] = bean.getCommand();
				cachedatas[i][2] = bean.getDir();
				cachedatas[i][3] = bean.getPort();
			}
		}
		return cachedatas;
	}
	
	public void remove(int rowindex){
		int size = cblist.size();
		if(rowindex < size){
			cblist.remove(rowindex);
		}
	}
	
	public void removes(Integer ...args){
		List<Object> waitForRemoves = new ArrayList<Object>();
		int size = cblist.size();
		if(null != args){
			for(int a : args){
				if(a < size){
					waitForRemoves.add( cblist.get(a) );
				}
			}
			cblist.removeAll(waitForRemoves);
		}
	}
	
	private void storeDataToJsonFile() throws IOException{
		if(null != cblist && cblist.size() > 0){
			String filepath = null;
//			filepath = getClass().getClassLoader()
//					.getResource(JSON_FILE_NAME).getPath();
			filepath = JSON_FILE_NAME;
			FileOutputStream fos = new FileOutputStream(filepath);
			JSON.writeJSONString(fos, cblist);
			fos.close();
		}
	}
	
	private void loadDataFromJsonFile() throws IOException{
		String filepath = null;
		try {
//			filepath = getClass().getClassLoader()
//						.getResource(JSON_FILE_NAME).getPath();
			filepath = JSON_FILE_NAME;
		} catch (Exception e) {
			cblist = new ArrayList<CommandBean>();
			return;
			//throw new RuntimeException(e);
		}
		if(null != filepath){
			BufferedReader br = null;
			br = new BufferedReader(new InputStreamReader(new FileInputStream(filepath)));
			String line = null;
			StringBuilder sbb = new StringBuilder();
			while((line=br.readLine())!=null){
				sbb.append(line);
				//sbb.append("\n");
			}
			cblist = JSON.parseArray(sbb.toString(), CommandBean.class);
			br.close();
		}
	}
	
	public List<CommandBean> getCblist() {
		return cblist;
	}

	public CommandBean get(int i){
		if(i < cblist.size()){
			return cblist.get(i);
		}else{
			return null;
		}
	}
	
	public void start(int i){
		cblist.get(i).setAlive(true);
	}
	
	public void stop(int i){
		cblist.get(i).setAlive(false);
	}
	
	/**
	 * 在`System.exit(0)`之前应该调用此方法结束子进程！
	 * (1) 关闭所有子进程
	 * (2) 设置所有的`isAlive=false`， 然后保存
	 */
	public void doSystemExit(){
		
	}
	
	@Test
	@Ignore
	public void test002(){
		CommandBeanJsonDB db = new CommandBeanJsonDB();
		db.data("firstblog", "cmd /c hexo server -p 5000", "C:/wxg2/firstblog", "5000");
		try {
			db.storeDataToJsonFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void test001(){
		try {
			loadDataFromJsonFile();
			for(CommandBean bean : cblist){
				System.out.println(bean);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
